#include "inc.h"

#include "cmdop.h"
#include "rl_cmd.h"
#include "sockop.h"

#define TEST_PATH "/tmp/.usock"

#define VTY_INDEX_TEST 0
#define VTY_INDEX_MAX  1

sockop_ctx_t g_ctx;

enum
{
    VIEW_NODE,
};

cmd_node_t view_node = {
    .node = VIEW_NODE,
    .prompt = "taotao > ",
};

int add_func(cmd_vty_t *vty, int argc, char *argv[])
{
    (void)vty;
    printf("add_func: argc = %d\n", argc);
    printf("add_func: %s, %s\n", argv[0], argv[1]);
    int a = atoi(argv[0]);
    int b = atoi(argv[1]);

    printf("a + b = %d\n", (a + b));

    return 0;
}

cmd_element_t add_cmd = {
    .string = "add A and B",
    .doc = "加运算",
    .exec = add_func,
};

int show_cpuinfo(cmd_vty_t *vty, int argc, char *argv[])
{
    (void)vty;
    (void)argc;
    (void)argv;

    char info[40960];

    FILE *fp;
    fp = fopen("/proc/cpuinfo", "r");
    if(fp)
    {   
        fread(info, sizeof(char),sizeof(info), fp);
        fclose(fp);
        printf("%s\n", info);
    }   
    return 0;
}

cmd_element_t show_cpuinfo_cmd = {
    .string = "show cpuinfo",
    .doc = "显示cpu信息",
    .exec = show_cpuinfo,
};

int show_meminfo(cmd_vty_t *vty, int argc, char *argv[])
{
    (void)vty;
    (void)argc;
    (void)argv;

    char info[40960];

    FILE *fp;
    fp = fopen("/proc/cpuinfo", "r");
    if(fp)
    {   
        fread(info, sizeof(char),sizeof(info), fp);
        fclose(fp);
        printf("%s\n", info);
    }   
    return 0;
}

#if 0
cmd_element_t show_meminfo_cmd = {
    .string = "show meminfo",
    .doc = "显示内存信息",
    .exec = show_meminfo,
};
#endif
int login_test(cmd_vty_t *vty, int argc, char *argv[])
{
    (void)vty;
    (void)argc;
    (void)argv;

    if (sockop_client_conn(&g_ctx) < 0)  
    {
        return CMD_WARNING; 
    }

    if (sockop_cmd_exec(g_ctx.sock, "set 1", stdout) < 0)
    {
        return CMD_WARNING; 
    }

    sockop_client_exit(&g_ctx);

    return CMD_SUCCESS;
}

cmd_element_t login_test_cmd = {
    .string = "login test",
    .doc = "登入test进程",
    .exec = login_test,
};

void command_install(cmd_vty_t *vty)
{
    cmd_install_element(vty->topvec, VIEW_NODE, &add_cmd);
    cmd_install_element(vty->topvec, VIEW_NODE, &show_cpuinfo_cmd);
    //cmd_install_element(vty->topvec, VIEW_NODE, &show_meminfo_cmd);
    cmd_install_element(vty->topvec, VIEW_NODE, &login_test_cmd);
}

void usock_init(void)
{
    if (sockop_usock_tostruct(TEST_PATH, &g_ctx.sun) < 0)
    {
        exit(-1);
    }

    g_ctx.type = SOCK_TYPE_UNIX;
    g_ctx.cache_size = 1024*1024;
}
int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;
    cmd_vty_t vty;

    usock_init();
    cmd_vty_init(&vty);

    vty.node = VIEW_NODE;

    cmd_install_node(&vty, &view_node);

    command_install(&vty);

    rl_cmd_init(&vty);
    rl_cmd_loop(&vty);

    return 0;
}

